<template>
  <div class="repository-detail-container">
    <div class="repository-header">
      <div class="header-left">
        <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
        <div class="repository-info">
          <h1 class="repository-name">
            <el-icon><Folder /></el-icon>
            {{ repository.name }}
          </h1>
          <p class="repository-description">{{ repository.description }}</p>
          <div class="repository-meta">
            <span class="owner">
              <el-icon><User /></el-icon>
              {{ repository.ownerName }}
            </span>
            <span class="visibility">
              <el-icon><Lock v-if="repository.isPrivate" /><Unlock v-else /></el-icon>
              {{ repository.isPrivate ? '私有' : '公开' }}
            </span>
            <span class="created-time">
              <el-icon><Clock /></el-icon>
              创建于 {{ formatTime(repository.createTime) }}
            </span>
          </div>
        </div>
      </div>
      
      <div class="header-actions">
        <el-button-group>
          <el-button icon="Star" :type="repository.isStarred ? 'primary' : 'default'" @click="toggleStar">
            <el-icon><StarFilled v-if="repository.isStarred" /><Star v-else /></el-icon>
            {{ repository.starCount || 0 }}
          </el-button>
          <el-button icon="Fork" @click="forkRepository">
            <el-icon><Share /></el-icon>
            {{ repository.forkCount || 0 }}
          </el-button>
          <el-button icon="Download" @click="cloneRepository">克隆</el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 仓库统计 -->
    <div class="repository-stats">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-icon branches">
              <el-icon><Branch /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ repository.branchCount || 0 }}</div>
              <div class="stat-label">分支</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-icon commits">
              <el-icon><Commit /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ repository.commitCount || 0 }}</div>
              <div class="stat-label">提交</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-icon contributors">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ repository.contributorCount || 0 }}</div>
              <div class="stat-label">贡献者</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-icon size">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ formatSize(repository.size) }}</div>
              <div class="stat-label">大小</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 仓库导航 -->
    <div class="repository-nav">
      <el-card>
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="代码" name="code">
            <div class="code-browser">
              <div class="branch-selector">
                <el-select v-model="currentBranch" placeholder="选择分支" @change="loadFiles">
                  <el-option 
                    v-for="branch in branches"
                    :key="branch.name"
                    :label="branch.name"
                    :value="branch.name"
                  />
                </el-select>
                <el-button @click="goToBranches">管理分支</el-button>
              </div>
              
              <div class="file-list">
                <div 
                  v-for="file in files"
                  :key="file.name"
                  class="file-item"
                  @click="openFile(file)"
                >
                  <div class="file-info">
                    <el-icon class="file-icon">
                      <Folder v-if="file.type === 'directory'" />
                      <Document v-else />
                    </el-icon>
                    <span class="file-name">{{ file.name }}</span>
                  </div>
                  <div class="file-meta">
                    <span class="commit-message">{{ file.lastCommit?.message }}</span>
                    <span class="commit-time">{{ formatTime(file.lastCommit?.time) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="提交" name="commits">
            <div class="commits-list">
              <div 
                v-for="commit in commits"
                :key="commit.id"
                class="commit-item"
              >
                <div class="commit-info">
                  <div class="commit-message">{{ commit.message }}</div>
                  <div class="commit-meta">
                    <span class="commit-author">{{ commit.author }}</span>
                    <span class="commit-time">{{ formatTime(commit.time) }}</span>
                    <span class="commit-hash">{{ commit.hash.substring(0, 8) }}</span>
                  </div>
                </div>
                <div class="commit-actions">
                  <el-button size="small" @click="viewCommit(commit)">查看</el-button>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="分支" name="branches">
            <div class="branches-list">
              <div 
                v-for="branch in branches"
                :key="branch.name"
                class="branch-item"
              >
                <div class="branch-info">
                  <div class="branch-name">
                    <el-icon><Branch /></el-icon>
                    {{ branch.name }}
                    <el-tag v-if="branch.isDefault" type="success" size="small">默认</el-tag>
                  </div>
                  <div class="branch-meta">
                    <span>{{ branch.commitCount }} 个提交</span>
                    <span>最后更新：{{ formatTime(branch.lastUpdate) }}</span>
                  </div>
                </div>
                <div class="branch-actions">
                  <el-button size="small" @click="switchBranch(branch)">切换</el-button>
                  <el-button size="small" type="danger" v-if="!branch.isDefault" @click="deleteBranch(branch)">删除</el-button>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="设置" name="settings">
            <div class="repository-settings">
              <el-form :model="repository" label-width="120px">
                <el-form-item label="仓库名称">
                  <el-input v-model="repository.name" />
                </el-form-item>
                <el-form-item label="仓库描述">
                  <el-input v-model="repository.description" type="textarea" :rows="3" />
                </el-form-item>
                <el-form-item label="可见性">
                  <el-radio-group v-model="repository.isPrivate">
                    <el-radio :label="false">公开</el-radio>
                    <el-radio :label="true">私有</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateRepository">保存设置</el-button>
                  <el-button type="danger" @click="deleteRepository">删除仓库</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getRepositoryDetail,
  getRepositoryBranches,
  getRepositoryCommits,
  getRepositoryFiles,
  starRepository,
  unstarRepository,
  forkRepository as apiForkRepository,
  updateRepository as apiUpdateRepository,
  deleteRepository as apiDeleteRepository
} from '@/api/version'
import { formatTime } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const repository = ref({})
const branches = ref([])
const commits = ref([])
const files = ref([])
const activeTab = ref('code')
const currentBranch = ref('main')

// 页面加载
onMounted(async () => {
  await loadRepository()
  await loadBranches()
  await loadCommits()
  await loadFiles()
})

// 加载仓库详情
const loadRepository = async () => {
  try {
    const response = await getRepositoryDetail(route.params.id)
    if (response.code === 200) {
      repository.value = response.data
    }
  } catch (error) {
    console.error('获取仓库详情失败:', error)
    ElMessage.error('获取仓库详情失败')
  }
}

// 加载分支列表
const loadBranches = async () => {
  try {
    const response = await getRepositoryBranches(route.params.id)
    if (response.code === 200) {
      branches.value = response.data || []
      if (branches.value.length > 0) {
        currentBranch.value = branches.value.find(b => b.isDefault)?.name || branches.value[0].name
      }
    }
  } catch (error) {
    console.error('获取分支列表失败:', error)
  }
}

// 加载提交记录
const loadCommits = async () => {
  try {
    const response = await getRepositoryCommits(route.params.id, { branch: currentBranch.value })
    if (response.code === 200) {
      commits.value = response.data || []
    }
  } catch (error) {
    console.error('获取提交记录失败:', error)
  }
}

// 加载文件列表
const loadFiles = async () => {
  try {
    const response = await getRepositoryFiles(route.params.id, { branch: currentBranch.value })
    if (response.code === 200) {
      files.value = response.data || []
    }
  } catch (error) {
    console.error('获取文件列表失败:', error)
  }
}

// 切换标签页
const handleTabChange = (tab) => {
  activeTab.value = tab
  if (tab === 'commits') {
    loadCommits()
  } else if (tab === 'branches') {
    loadBranches()
  }
}

// 切换收藏
const toggleStar = async () => {
  try {
    if (repository.value.isStarred) {
      await unstarRepository(repository.value.id)
      repository.value.isStarred = false
      repository.value.starCount = (repository.value.starCount || 1) - 1
      ElMessage.success('已取消收藏')
    } else {
      await starRepository(repository.value.id)
      repository.value.isStarred = true
      repository.value.starCount = (repository.value.starCount || 0) + 1
      ElMessage.success('已添加收藏')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// Fork 仓库
const forkRepository = async () => {
  try {
    await apiForkRepository(repository.value.id)
    ElMessage.success('Fork 成功')
    repository.value.forkCount = (repository.value.forkCount || 0) + 1
  } catch (error) {
    console.error('Fork 失败:', error)
    ElMessage.error('Fork 失败')
  }
}

// 克隆仓库
const cloneRepository = () => {
  const cloneUrl = `git clone ${repository.value.cloneUrl || ''}`
  navigator.clipboard.writeText(cloneUrl).then(() => {
    ElMessage.success('克隆命令已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 打开文件
const openFile = (file) => {
  if (file.type === 'directory') {
    // 进入目录
    router.push(`/version/repository/${route.params.id}/tree/${currentBranch.value}/${file.path}`)
  } else {
    // 查看文件
    router.push(`/version/repository/${route.params.id}/blob/${currentBranch.value}/${file.path}`)
  }
}

// 查看提交
const viewCommit = (commit) => {
  router.push(`/version/repository/${route.params.id}/commit/${commit.hash}`)
}

// 切换分支
const switchBranch = (branch) => {
  currentBranch.value = branch.name
  loadFiles()
  loadCommits()
}

// 删除分支
const deleteBranch = async (branch) => {
  try {
    await ElMessageBox.confirm(`确认要删除分支 ${branch.name} 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用删除分支API
    ElMessage.success('分支删除成功')
    loadBranches()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分支失败:', error)
      ElMessage.error('删除分支失败')
    }
  }
}

// 跳转到分支管理
const goToBranches = () => {
  router.push(`/version/repository/${route.params.id}/branches`)
}

// 更新仓库
const updateRepository = async () => {
  try {
    await apiUpdateRepository(repository.value.id, repository.value)
    ElMessage.success('设置保存成功')
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error('保存设置失败')
  }
}

// 删除仓库
const deleteRepository = async () => {
  try {
    await ElMessageBox.confirm('确认要删除此仓库吗？此操作不可逆！', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await apiDeleteRepository(repository.value.id)
    ElMessage.success('仓库删除成功')
    router.push('/version')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除仓库失败:', error)
      ElMessage.error('删除仓库失败')
    }
  }
}

// 工具函数
const formatSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 返回
const goBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.repository-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.repository-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .header-left {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    flex: 1;
    
    .repository-info {
      .repository-name {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 24px;
        font-weight: 600;
        margin: 0 0 8px 0;
        color: #303133;
      }
      
      .repository-description {
        color: #606266;
        margin: 0 0 16px 0;
      }
      
      .repository-meta {
        display: flex;
        align-items: center;
        gap: 20px;
        flex-wrap: wrap;
        
        span {
          display: flex;
          align-items: center;
          gap: 4px;
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }
}

.repository-stats {
  margin-bottom: 20px;
  
  .stat-card {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 16px;
    
    .stat-icon {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      
      &.branches {
        background-color: #e1f3ff;
        color: #409eff;
      }
      
      &.commits {
        background-color: #e1f9e1;
        color: #67c23a;
      }
      
      &.contributors {
        background-color: #fdf6ec;
        color: #e6a23c;
      }
      
      &.size {
        background-color: #fef0f0;
        color: #f56c6c;
      }
    }
    
    .stat-content {
      .stat-number {
        font-size: 20px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .stat-label {
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

.repository-nav {
  .branch-selector {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .file-list,
  .commits-list,
  .branches-list {
    .file-item,
    .commit-item,
    .branch-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:hover {
        background-color: #f8f9fa;
      }
      
      .file-info,
      .commit-info,
      .branch-info {
        display: flex;
        align-items: center;
        gap: 8px;
        flex: 1;
        
        .file-icon {
          color: #409eff;
        }
        
        .file-name,
        .commit-message,
        .branch-name {
          font-weight: 500;
          color: #303133;
        }
        
        .commit-meta,
        .branch-meta {
          display: flex;
          gap: 12px;
          font-size: 12px;
          color: #909399;
          margin-top: 4px;
        }
      }
      
      .file-meta {
        text-align: right;
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

@media (max-width: 768px) {
  .repository-detail-container {
    padding: 10px;
  }
  
  .repository-header {
    flex-direction: column;
    gap: 20px;
    padding: 20px;
  }
  
  .repository-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .stat-card {
    flex-direction: column;
    text-align: center;
  }
}
</style>
